<%@ page contentType="text/html;charset=UTF-8" %>
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>

    <head>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script>
        $(document).ready(function () {
          console.log("页面加载完成，jQuery版本:", $.fn.jquery);

          // 提交表单
          $("#btn_register_admin").click(function () {
            console.log("注册按钮被点击");

            // 阻止默认行为
            event.preventDefault();
            var admin_name = $.trim($("#input_admin_name").val());
            var admin_nickname = $.trim($("#input_admin_nickname").val());
            var admin_password = $.trim($("#input_admin_password").val());
            var admin_password_confirm = $.trim($("#input_admin_password_confirm").val());

            // 表单验证
            if (!admin_name) {
              alert("请输入用户名");
              $("#input_admin_name").focus();
              return;
            }

            if (admin_name.length < 3) {
              alert("用户名长度不能少于3位");
              $("#input_admin_name").focus();
              return;
            }

            if (!admin_nickname) {
              alert("请输入昵称");
              $("#input_admin_nickname").focus();
              return;
            }

            if (!admin_password) {
              alert("请输入密码");
              $("#input_admin_password").focus();
              return;
            }

            if (admin_password.length < 6) {
              alert("密码长度不能少于6位");
              $("#input_admin_password").focus();
              return;
            }

            if (!admin_password_confirm) {
              alert("请确认密码");
              $("#input_admin_password_confirm").focus();
              return;
            }

            if (admin_password !== admin_password_confirm) {
              alert("两次输入的密码不一致");
              $("#input_admin_password_confirm").focus();
              return;
            }

            // 创建FormData对象用于文件上传
            var formData = new FormData();
            var profilePicture = $("#input_profile_picture")[0].files[0];
            if (profilePicture) {
              // 验证文件类型
              var allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
              if (allowedTypes.indexOf(profilePicture.type) === -1) {
                alert("请选择图片文件（JPG、PNG、GIF格式）");
                return;
              }

              // 验证文件大小（限制为2MB）
              if (profilePicture.size > 2 * 1024 * 1024) {
                alert("图片大小不能超过2MB");
                return;
              }

              formData.append("profile_picture", profilePicture);
            }

            // 添加其他表单数据
            formData.append("admin_name", admin_name);
            formData.append("admin_nickname", admin_nickname);
            formData.append("admin_password", admin_password);

            // 禁用按钮防止重复提交
            $("#btn_register_admin").attr("disabled", true).val("注册中...");

            console.log("准备发送AJAX请求");
            console.log("FormData内容:", formData);

            $.ajax({
              url: "${pageContext.request.contextPath}/admin/register",
              type: "POST",
              data: formData,
              processData: false,
              contentType: false,
              dataType: "json",
              success: function (data) {
                console.log("AJAX请求成功，返回数据:", data);
                $("#btn_register_admin").attr("disabled", false).val("注册");

                try {
                  var result;
                  if (typeof data === 'string') {
                    result = JSON.parse(data);
                  } else {
                    result = data;
                  }

                  if (result.success) {
                    alert("注册成功！请登录");
                    window.location.href = "${pageContext.request.contextPath}/admin/login";
                  } else {
                    alert("注册失败：" + (result.message || "未知错误"));
                  }
                } catch (e) {
                  console.log("解析返回数据失败:", e);
                  alert("注册失败，请稍后再试！");
                }
              },
              error: function (xhr, status, error) {
                $("#btn_register_admin").attr("disabled", false).val("注册");
                console.log("AJAX请求失败:");
                console.log("状态:", status);
                console.log("错误:", error);
                console.log("响应文本:", xhr.responseText);
                console.log("状态码:", xhr.status);
                alert("操作失败，请稍后再试！错误信息: " + error);
              }
            });
          });

          // 返回登录页
          $("#btn_back_to_login").click(function () {
            window.location.href = "${pageContext.request.contextPath}/admin/login";
          });

          // 预览头像
          $("#input_profile_picture").change(function () {
            var file = this.files[0];
            if (file) {
              var reader = new FileReader();
              reader.onload = function (e) {
                $("#img_preview").attr("src", e.target.result).show();
              }
              reader.readAsDataURL(file);
            } else {
              $("#img_preview").hide();
            }
          });
        });
      </script>
      <style>
        .register-container {
          width: 450px;
          margin: 50px auto;
          padding: 30px;
          background-color: #fff;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .register-title {
          text-align: center;
          margin-bottom: 30px;
          color: #333;
          font-size: 24px;
          font-weight: bold;
        }

        .form-group {
          margin-bottom: 20px;
        }

        .form-label {
          display: block;
          margin-bottom: 8px;
          font-weight: bold;
          color: #555;
        }

        .form-input {
          width: 100%;
          padding: 12px;
          border: 1px solid #ddd;
          border-radius: 4px;
          box-sizing: border-box;
          font-size: 14px;
          transition: border-color 0.3s;
        }

        .form-input:focus {
          border-color: #007bff;
          outline: none;
        }

        .form-btn {
          width: 100%;
          padding: 12px;
          border: none;
          border-radius: 4px;
          margin-top: 10px;
          cursor: pointer;
          font-size: 16px;
          font-weight: bold;
          transition: background-color 0.3s;
        }

        .btn-primary {
          background-color: #007bff;
          color: white;
        }

        .btn-primary:hover {
          background-color: #0056b3;
        }

        .btn-primary:disabled {
          background-color: #6c757d;
          cursor: not-allowed;
        }

        .btn-secondary {
          background-color: #6c757d;
          color: white;
        }

        .btn-secondary:hover {
          background-color: #545b62;
        }

        .profile-picture-container {
          text-align: center;
          margin-bottom: 25px;
        }

        .profile-picture-preview {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          object-fit: cover;
          margin-bottom: 15px;
          display: none;
          border: 3px solid #ddd;
        }

        .file-input-wrapper {
          position: relative;
          display: inline-block;
        }

        .file-input-label {
          display: inline-block;
          padding: 8px 16px;
          background-color: #f8f9fa;
          border: 1px solid #ddd;
          border-radius: 4px;
          cursor: pointer;
          color: #495057;
          transition: background-color 0.3s;
        }

        .file-input-label:hover {
          background-color: #e9ecef;
        }

        .file-input {
          position: absolute;
          left: -9999px;
        }

        .login-link {
          text-align: center;
          margin-top: 20px;
          color: #666;
        }

        .login-link a {
          color: #007bff;
          text-decoration: none;
        }

        .login-link a:hover {
          text-decoration: underline;
        }

        .required {
          color: #dc3545;
        }
      </style>
    </head>

    <body>
      <div class="register-container">
        <h2 class="register-title">管理员注册</h2>

        <div class="profile-picture-container">
          <img id="img_preview" class="profile-picture-preview" src="" alt="头像预览" />
          <div class="file-input-wrapper">
            <label for="input_profile_picture" class="file-input-label">选择头像（可选）</label>
            <input type="file" id="input_profile_picture" class="file-input" accept="image/*" />
          </div>
        </div>

        <div class="form-group">
          <label class="form-label" for="input_admin_name">用户名 <span class="required">*</span></label>
          <input class="form-input" id="input_admin_name" type="text" placeholder="请输入用户名（至少3位）" maxlength="20" />
        </div>

        <div class="form-group">
          <label class="form-label" for="input_admin_nickname">昵称 <span class="required">*</span></label>
          <input class="form-input" id="input_admin_nickname" type="text" placeholder="请输入昵称" maxlength="30" />
        </div>

        <div class="form-group">
          <label class="form-label" for="input_admin_password">密码 <span class="required">*</span></label>
          <input class="form-input" id="input_admin_password" type="password" placeholder="请输入密码（至少6位）"
            maxlength="50" />
        </div>

        <div class="form-group">
          <label class="form-label" for="input_admin_password_confirm">确认密码 <span class="required">*</span></label>
          <input class="form-input" id="input_admin_password_confirm" type="password" placeholder="请再次输入密码"
            maxlength="50" />
        </div>

        <input type="button" class="form-btn btn-primary" id="btn_register_admin" value="注册" />
        <input type="button" class="form-btn btn-secondary" id="btn_back_to_login" value="返回登录" />

        <div class="login-link">
          已有账号？<a href="${pageContext.request.contextPath}/admin/login">立即登录</a>
        </div>
      </div>
    </body>

    </html>